import React, { useState, useEffect } from 'react';
import MDEditor from '@uiw/react-md-editor';
import { useNavigate } from 'react-router-dom';
import { categoryApi, articleApi } from '../../api/knowledge';
import { message, Modal, Button, Input } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import './index.css';

const MarkdownEditor = () => {
  const [value, setValue] = useState("");
  const [title, setTitle] = useState("");
  const [summary, setSummary] = useState("");
  const [categoryOneId, setCategoryOneId] = useState("");
  const [categoryTwoId, setCategoryTwoId] = useState("");
  const [categoryOneList, setCategoryOneList] = useState([]);
  const [categoryTwoList, setCategoryTwoList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState("");
  const [addingCategory, setAddingCategory] = useState(false);
  const [isLevelTwoModalVisible, setIsLevelTwoModalVisible] = useState(false);
  const [newLevelTwoName, setNewLevelTwoName] = useState("");
  const [addingLevelTwoCategory, setAddingLevelTwoCategory] = useState(false);
  const navigate = useNavigate();

  // 加载一级分类
  useEffect(() => {
    const loadCategories = async () => {
      try {
        const res = await categoryApi.getAllLevelOne();
        setCategoryOneList(res || []);
      } catch (error) {
        console.error('加载分类失败:', error);
        message.error('加载分类失败');
      }
    };
    loadCategories();
  }, []);

  // 当一级分类变化时加载二级分类
  useEffect(() => {
    const loadSubCategories = async () => {
      if (!categoryOneId) {
        setCategoryTwoList([]);
        setCategoryTwoId('');
        return;
      }
      try {
        const res = await categoryApi.getLevelTwoByParentId(categoryOneId);
        setCategoryTwoList(res || []);
        setCategoryTwoId('');
      } catch (error) {
        console.error('加载子分类失败:', error);
        message.error('加载子分类失败');
      }
    };
    loadSubCategories();
  }, [categoryOneId]);

  const handleSave = async () => {
    if (!title.trim()) {
      message.warning('请输入标题');
      return;
    }
    if (!categoryOneId) {
      message.warning('请选择一级分类');
      return;
    }
    if (!categoryTwoId) {
      message.warning('请选择二级分类');
      return;
    }
    if (!value.trim()) {
      message.warning('请输入内容');
      return;
    }

    try {
      setLoading(true);
      const articleId = await articleApi.createArticle({
        categoryOneId: parseInt(categoryOneId),
        categoryTwoId: parseInt(categoryTwoId),
        content: value,
        status: 1,
        summary: summary || value.slice(0, 100) + (value.length > 100 ? '...' : ''),
        title: title.trim(),
        useCount: 0,
        viewCount: 0
      });
      
      message.success('创建成功');
      // 如果成功获取到文章ID，跳转到文章详情页
      if (articleId) {
        navigate(`/article/${articleId}`);
      } else {
        navigate('/');
      }
    } catch (error) {
      console.error('保存失败:', error);
      message.error(error.message || '保存失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    if (window.confirm('确定要放弃当前编辑的内容吗？')) {
      navigate(-1); // Go back to previous page
    }
  };
  
  // 显示添加一级分类的对话框
  const showAddCategoryModal = () => {
    setIsModalVisible(true);
    setNewCategoryName('');
  };
  
  // 关闭对话框
  const handleModalCancel = () => {
    setIsModalVisible(false);
    setNewCategoryName('');
  };
  
  // 创建新的一级分类
  const handleAddCategory = async () => {
    if (!newCategoryName.trim()) {
      message.warning('请输入分类名称');
      return;
    }
    
    try {
      setAddingCategory(true);
      await categoryApi.createLevelOne({ name: newCategoryName.trim() });
      message.success('创建分类成功');
      
      // 重新加载一级分类列表
      const res = await categoryApi.getAllLevelOne();
      setCategoryOneList(res || []);
      
      // 自动选择新创建的分类
      const newCategory = res.find(item => item.name === newCategoryName.trim());
      if (newCategory) {
        setCategoryOneId(newCategory.id);
      }
      
      // 关闭对话框
      setIsModalVisible(false);
      setNewCategoryName('');
    } catch (error) {
      console.error('创建分类失败:', error);
      message.error(error.message || '创建分类失败');
    } finally {
      setAddingCategory(false);
    }
  };
  
  // 显示添加二级分类的对话框
  const showAddLevelTwoModal = () => {
    if (!categoryOneId) {
      message.warning('请先选择一级分类');
      return;
    }
    setIsLevelTwoModalVisible(true);
    setNewLevelTwoName('');
  };
  
  // 关闭二级分类对话框
  const handleLevelTwoModalCancel = () => {
    setIsLevelTwoModalVisible(false);
    setNewLevelTwoName('');
  };
  
  // 创建新的二级分类
  const handleAddLevelTwoCategory = async () => {
    if (!categoryOneId) {
      message.warning('请先选择一级分类');
      return;
    }
    
    if (!newLevelTwoName.trim()) {
      message.warning('请输入二级分类名称');
      return;
    }
    
    try {
      setAddingLevelTwoCategory(true);
      await categoryApi.createLevelTwo({ 
        name: newLevelTwoName.trim(),
        parentId: parseInt(categoryOneId)
      });
      message.success('创建二级分类成功');
      
      // 重新加载二级分类列表
      const res = await categoryApi.getLevelTwoByParentId(categoryOneId);
      setCategoryTwoList(res || []);
      
      // 自动选择新创建的分类
      const newCategory = res.find(item => item.name === newLevelTwoName.trim());
      if (newCategory) {
        setCategoryTwoId(newCategory.id);
      }
      
      // 关闭对话框
      setIsLevelTwoModalVisible(false);
      setNewLevelTwoName('');
    } catch (error) {
      console.error('创建二级分类失败:', error);
      message.error(error.message || '创建二级分类失败');
    } finally {
      setAddingLevelTwoCategory(false);
    }
  };

  return (
    <div className="markdown-editor-container">
      <div className="editor-header">
        <h2>新建知识点</h2>
        <div className="editor-actions">
          <button className="cancel-btn" onClick={handleCancel} disabled={loading}>
            取消
          </button>
          <button 
            className="save-btn" 
            onClick={handleSave} 
            disabled={!title.trim() || !value.trim() || !categoryOneId || !categoryTwoId || loading}
          >
            {loading ? '保存中...' : '保存'}
          </button>
        </div>
      </div>
      
      <div className="editor-form">
        <div className="form-group">
          <label>标题*</label>
          <input
            type="text"
            className="form-control"
            placeholder="输入标题..."
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>
        
        <div className="form-row">
          <div className="form-group">
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '5px' }}>
              <label style={{ marginBottom: 0, marginRight: '10px' }}>一级分类*</label>
              <Button 
                type="primary" 
                size="small" 
                icon={<PlusOutlined />} 
                onClick={showAddCategoryModal}
                disabled={loading}
              >
                新增
              </Button>
            </div>
            <select 
              className="form-control"
              value={categoryOneId}
              onChange={(e) => setCategoryOneId(e.target.value)}
              disabled={loading}
            >
              <option value="">请选择一级分类</option>
              {categoryOneList.map(item => (
                <option key={item.id} value={item.id}>{item.name}</option>
              ))}
            </select>
          </div>
          
          <div className="form-group">
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '5px' }}>
              <label style={{ marginBottom: 0, marginRight: '10px' }}>二级分类*</label>
              <Button 
                type="primary" 
                size="small" 
                icon={<PlusOutlined />} 
                onClick={showAddLevelTwoModal}
                disabled={!categoryOneId || loading}
              >
                新增
              </Button>
            </div>
            <select 
              className="form-control"
              value={categoryTwoId}
              onChange={(e) => setCategoryTwoId(e.target.value)}
              disabled={!categoryOneId || loading}
            >
              <option value="">请选择二级分类</option>
              {categoryTwoList.map(item => (
                <option key={item.id} value={item.id}>{item.name}</option>
              ))}
            </select>
          </div>
        </div>
        
        <div className="form-group">
          <label>摘要</label>
          <textarea
            className="form-control"
            placeholder="输入摘要，如不填写将自动截取文章前100字..."
            rows="3"
            value={summary}
            onChange={(e) => setSummary(e.target.value)}
          />
        </div>
      </div>

      <div className="editor-content">
        <MDEditor
          value={value}
          onChange={setValue}
          height="100%"
          fullscreen={false}
          previewOptions={{
            rehypePlugins: [],
          }}
          textareaProps={{
            placeholder: '在此输入内容，支持Markdown语法...',
          }}
        />
      </div>
      
      {/* 添加一级分类的对话框 */}
      <Modal
        title="新增一级分类"
        open={isModalVisible}
        onOk={handleAddCategory}
        onCancel={handleModalCancel}
        confirmLoading={addingCategory}
        okText="确定"
        cancelText="取消"
      >
        <Input
          placeholder="请输入分类名称"
          value={newCategoryName}
          onChange={(e) => setNewCategoryName(e.target.value)}
          onPressEnter={handleAddCategory}
          disabled={addingCategory}
        />
      </Modal>
      
      {/* 添加二级分类的对话框 */}
      <Modal
        title="新增二级分类"
        open={isLevelTwoModalVisible}
        onOk={handleAddLevelTwoCategory}
        onCancel={handleLevelTwoModalCancel}
        confirmLoading={addingLevelTwoCategory}
        okText="确定"
        cancelText="取消"
      >
        <Input
          placeholder="请输入二级分类名称"
          value={newLevelTwoName}
          onChange={(e) => setNewLevelTwoName(e.target.value)}
          onPressEnter={handleAddLevelTwoCategory}
          disabled={addingLevelTwoCategory}
        />
      </Modal>
    </div>
  );
};

export default MarkdownEditor;
